package com.lobaby.tools.common.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * PDF 生成的工具类
 * 
 * @author yuyongjiang
 */
@Component
public class PdfUtils {
	private final static Logger LOGGER = LoggerFactory.getLogger(PdfUtils.class);

	public static String picToPdf(String imgPath) throws Exception {
		return picToPdf(imgPath, true);
	}

	/**
	 * 图片转pdf
	 * @param imgPath
	 * @param isDirectory
	 * @return
	 * @throws Exception
	 */
	public static String picToPdf(String imgPath, boolean isDirectory) throws Exception {
		File file = new File(imgPath);
		if (!file.exists()) {
			return "";
		}

		String targetPath = new String();
		File imgFile = null;
		// 确定targetPath，使用给定的目录值名文件名
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			if (isDirectory) {
				imgFile = file;
			} else {
				if (files.length > 0) {
					imgFile = files[0];
				}
			}
		} else {
			imgFile = file;
		}

		if (imgFile != null) {
			String path = imgFile.getAbsolutePath();
			String suffix = path.substring(0, path.lastIndexOf(File.separator));
			targetPath = suffix + File.separator + imgFile.getName() + ".pdf";
			picToPdf(imgPath, targetPath);
			return targetPath;
		} else {
			return "";
		}
	}

	public static void picToPdf(String imgPath, String targetPath) throws Exception {
		File file = new File(imgPath);
		if (!file.exists()) {
			return;
		}

		List<File> imgs = new ArrayList<>();
		if (file.isDirectory()) {
			imgs = Stream.of(file.listFiles()).filter(PdfUtils::isPic).sorted((x,y) -> x.getName().compareToIgnoreCase(y.getName())).collect(Collectors.toList());
		} else {
			if (isPic(file)) {
				imgs.add(file);
			}
		}

		if (imgs.size() > 0) {
			OutputStream os = new FileOutputStream(new File(targetPath));
			// 初始化 Document 对象
			Document doc = new Document(null, 0, 0, 0, 0);
			PdfWriter.getInstance(doc, os);
			// 设置PageSize
			Image image = Image.getInstance(imgs.get(0).getAbsolutePath());
			doc.setPageSize(new Rectangle(image.getScaledWidth(), image.getScaledHeight()));
			doc.open();

			try {
				for (File imgFile : imgs) {
					try {
						Image img = Image.getInstance(imgFile.getAbsolutePath());
						img.setAlignment(Image.ALIGN_CENTER);
						doc.newPage();
						doc.add(img);
					} catch(Exception e) {
						e.printStackTrace();
					}
				}

			} catch (Exception e) {
			    e.printStackTrace();
			} finally {
				doc.close();
				os.flush();
				os.close();
			}
		}
	}

	public static boolean isPic(File file) {
		if (file == null) {
			return false;
		}

		if (file.getName().endsWith(".png")
				|| file.getName().endsWith(".jpg")
				|| file.getName().endsWith(".gif")
				|| file.getName().endsWith(".jpeg")
				|| file.getName().endsWith(".tif")) {
			return true;
		} else {
			return false;
		}
	}

	public static List<String> convertToPic(InputStream is, String filePrefix, String outputPath) {
		List<String> result = new ArrayList<String>();

		try {
			PDDocument doc = PDDocument.load(is);
			PDFRenderer renderer = new PDFRenderer(doc);

			File output = new File(outputPath);
			if (!output.exists()) {
				output.mkdirs();
			}

			int pageCount = doc.getNumberOfPages();
			int addZeroLength = String.valueOf(pageCount).length();
			System.out.println(pageCount);
			for (int i = 0; i < pageCount; i++) {
				// 按页转换pdf为图片，输出至指定路径
				BufferedImage image = renderer.renderImageWithDPI(i, 150);

				String suffix = StringUtil.addZeroLeft(i+"", addZeroLength);
				String outputname = filePrefix + "-" + suffix + ".jpg";
				File out = new File(output, outputname);
				ImageIO.write(image, "JPG", out);

				result.add(out.getAbsolutePath());
			}
		} catch (Exception e) {
			LOGGER.error("", e);
		}

		return result;
	}

	public static List<String> convertToPic(String pdfpath, String outputPath) throws Exception {
		File file = new File(pdfpath);
		if (!file.exists()) {
			return null;
		}

		return convertToPic(new FileInputStream(file), StringUtil.getFileName(file), outputPath);
	}

}
